package com.ychen.nttey.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @Author chenyuliao
 * @Date 2020/5/15 20:41
 */
public class GroupChatServer {
    private int port = 6666;

    GroupChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            ChannelPipeline pipeline = sc.pipeline();
                            // 解码编码
                            pipeline.addLast(new HttpServerCodec());

                            // 以块的方式写
                            pipeline.addLast(new ChunkedWriteHandler());

                            // http数据在传输中是分段的,HttpObjectAggregator 就可以聚合，http当数据量很大是，就会分段
                            pipeline.addLast(new HttpObjectAggregator(8192));

        /*  1、websocket 数据是以帧的形式传递
            2、可以看到WebSocketFrame有6个子类
            3、浏览器请求：ws://localhost:7000/xxx
            4、WebSocketServerProtocolHandler，核心功能讲http协议升级为ws协议，保持长连接
        */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/test"));

                            // 自定义handler，处理业务逻辑
                            pipeline.addLast(new MyTextWebSocketFrameHandler());
                        }
                    });
            System.out.println("netty 服务器启动");
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            // 监听关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }


}
